package com.stars.easyms.datasource.loadbalancer;

import com.stars.easyms.datasource.EasyMsDataSource;
import com.stars.easyms.datasource.EasyMsDataSourceSet;

/**
 * <p>enumName: LoadBalancer</p>
 * <p>description: 数据源负载均衡枚举类</p>
 *
 * @author guoguifang
 * @date 2019-11-20 18:20
 * @since 1.4.0
 */
public enum LoadBalancer {

    /**
     * 主备模式
     */
    ACTIVE_STANDBY("active_standby", new ActiveStandbyDataSourceLoadBalancer()),

    /**
     * 最可利用模式
     */
    BEST_AVAILABLE("best-available", new BestAvailableDataSourceLoadBalancer()),

    /**
     * 轮询模式
     */
    ROUND_ROBIN("round_robin", new RoundRobinDataSourceLoadBalancer()),

    /**
     * 随机模式
     */
    RANDOM("random", new RandomDataSourceLoadBalancer());

    private String code;

    private DataSourceLoadBalancer dataSourceLoadBalancer;

    LoadBalancer(String code, DataSourceLoadBalancer dataSourceLoadBalancer) {
        this.code = code;
        this.dataSourceLoadBalancer = dataSourceLoadBalancer;
    }

    public String getCode() {
        return code;
    }

    public EasyMsDataSource getDataSource(EasyMsDataSourceSet easyMsDataSourceSet) {
        return dataSourceLoadBalancer.getDataSource(easyMsDataSourceSet);
    }

    public static LoadBalancer forCode(String loadBalancer, LoadBalancer defaultLoadBalancer) {
        if (ACTIVE_STANDBY.code.equalsIgnoreCase(loadBalancer)) {
            return ACTIVE_STANDBY;
        } else if (BEST_AVAILABLE.code.equalsIgnoreCase(loadBalancer)) {
            return BEST_AVAILABLE;
        } else if (RANDOM.code.equalsIgnoreCase(loadBalancer)) {
            return RANDOM;
        } else if (ROUND_ROBIN.code.equalsIgnoreCase(loadBalancer)) {
            return ROUND_ROBIN;
        }
        return defaultLoadBalancer;
    }
}
